<?php
/**
 * При необходимости создает ведущий нуль двузначного числа
 *
 * @param int $i
 * @return string
 */
function zeros( $i ) {
  return (int)$i < 10 ? '0'.(int)$i : (string)$i;
}


/**
 * Преобразовывает дату в формате Unix Timestamp
 * в форматирование MySQL
 *
 * @param int timestamp
 * @return date_string
 */
function nix2mydate( $timestamp=NULL ) {
  if ( empty($timestamp) )
  $timestamp = time();
  return strftime("%Y-%m-%d", $timestamp);
}


function my2nix($mydate) {
  $mydate = explode(" ", $mydate);
  $date = explode("-", $mydate[0]);
  $time = explode(":", $mydate[1]);
  return mktime($time[0]+0,$time[1]+0,$time[2]+0,$date[1]+0,$date[2]+0,$date[0]+0);
}

function mydate2nix($mydate)
{
  $date = explode("-", $mydate);
  return mktime(23,0,0,$date[1]+0,$date[2]+0,$date[0]+0);
}


/**
 * Преобразовывает дату и время в формате Unix Timestamp
 * в форматирование MySQL
 *
 * @param int timestamp
 * @return date_string
 */
function nix2my( $timestamp=NULL )
{
  if ( empty($timestamp) )
  $timestamp = time();
  return strftime("%Y-%m-%d %T", $timestamp);
}



function ConvertBMP2GD($src, $dest = false) {
  if(!($src_f = fopen($src, "rb"))) {
    return false;
  }
  if(!($dest_f = fopen($dest, "wb"))) {
    return false;
  }
  $header = unpack("vtype/Vsize/v2reserved/Voffset", fread($src_f,
  14));
  $info = unpack("Vsize/Vwidth/Vheight/vplanes/vbits/Vcompression/Vimagesize/Vxres/Vyres/Vncolor/Vimportant",
  fread($src_f, 40));

  extract($info);
  extract($header);

  if($type != 0x4D42) { // signature "BM"
    return false;
  }

  $palette_size = $offset - 54;
  $ncolor = $palette_size / 4;
  $gd_header = "";
  // true-color vs. palette
  $gd_header .= ($palette_size == 0) ? "\xFF\xFE" : "\xFF\xFF";
  $gd_header .= pack("n2", $width, $height);
  $gd_header .= ($palette_size == 0) ? "\x01" : "\x00";
  if($palette_size) {
    $gd_header .= pack("n", $ncolor);
  }
  // no transparency
  $gd_header .= "\xFF\xFF\xFF\xFF";

  fwrite($dest_f, $gd_header);

  if($palette_size) {
    $palette = fread($src_f, $palette_size);
    $gd_palette = "";
    $j = 0;
    while($j < $palette_size) {
      $b = $palette{$j++};
      $g = $palette{$j++};
      $r = $palette{$j++};
      $a = $palette{$j++};
      $gd_palette .= "$r$g$b$a";
    }
    $gd_palette .= str_repeat("\x00\x00\x00\x00", 256 - $ncolor);
    fwrite($dest_f, $gd_palette);
  }

  $scan_line_size = (($bits * $width) + 7) >> 3;
  $scan_line_align = ($scan_line_size & 0x03) ? 4 - ($scan_line_size &
  0x03) : 0;

  for($i = 0, $l = $height - 1; $i < $height; $i++, $l--) {
    // BMP stores scan lines starting from bottom
    fseek($src_f, $offset + (($scan_line_size + $scan_line_align) *
    $l));
    $scan_line = fread($src_f, $scan_line_size);
    if($bits == 24) {
      $gd_scan_line = "";
      $j = 0;
      while($j < $scan_line_size) {
        $b = $scan_line{$j++};
        $g = $scan_line{$j++};
        $r = $scan_line{$j++};
        $gd_scan_line .= "\x00$r$g$b";
      }
    }
    else if($bits == 8) {
      $gd_scan_line = $scan_line;
    }
    else if($bits == 4) {
      $gd_scan_line = "";
      $j = 0;
      while($j < $scan_line_size) {
        $byte = ord($scan_line{$j++});
        $p1 = chr($byte >> 4);
        $p2 = chr($byte & 0x0F);
        $gd_scan_line .= "$p1$p2";
      } $gd_scan_line = substr($gd_scan_line, 0, $width);
    }
    else if($bits == 1) {
      $gd_scan_line = "";
      $j = 0;
      while($j < $scan_line_size) {
        $byte = ord($scan_line{$j++});
        $p1 = chr((int) (($byte & 0x80) != 0));
        $p2 = chr((int) (($byte & 0x40) != 0));
        $p3 = chr((int) (($byte & 0x20) != 0));
        $p4 = chr((int) (($byte & 0x10) != 0));
        $p5 = chr((int) (($byte & 0x08) != 0));
        $p6 = chr((int) (($byte & 0x04) != 0));
        $p7 = chr((int) (($byte & 0x02) != 0));
        $p8 = chr((int) (($byte & 0x01) != 0));
        $gd_scan_line .= "$p1$p2$p3$p4$p5$p6$p7$p8";
      } $gd_scan_line = substr($gd_scan_line, 0, $width);
    }

    fwrite($dest_f, $gd_scan_line);
  }
  fclose($src_f);
  fclose($dest_f);
  return true;
}

function imagecreatefrombmp($filename) {
  $tmp_name = tempnam("upload/", "GD");
  if(ConvertBMP2GD($filename, $tmp_name)) {
    $img = imagecreatefromgd($tmp_name);
    unlink($tmp_name);
    return $img;
  } return false;
}

function format_text( $text ) {
//  $text = str_replace( '<cut>', '', $text );
  $text = str_replace( "\r", '', $text );
  $text = explode( "\n\n", $text );
  foreach( $text as &$block ) {
    $l = strlen( $block );
    if ( $l>5 && $block[0]=='<' && $block[1]=='h' && $block[3]=='>' && $block[$l-1]=='>' && $block[$l-3]=='h' && $block[$l-4]=='/' && $block[$l-5]=='<' ) {
    } else {
      $block = '<p>' . str_replace( "\n", "<br/>\n", $block ) . '</p>';
    }
  }
  $text = implode( "\n\n", $text );
  return $text;
}

function cut( $text ) {
  $text = explode( '<cut>', $text );
  return $text[0];
}




function is( &$condition, $then=null, $else=null ) {
  if ( isset($condition) && $condition ) {
    return $then||$else ? $then : $condition;
  }
  return $else;
}

function isor( $condition, $else ) {
  return $condition ? $condition : $else;
}


function translit ($str)
{
  $a = array (
            "А" => "a",            "Б" => "b",
            "В" => "v",            "Г" => "g",
            "Д" => "d",            "Е" => "e",
            "Ё" => "e",            "Ж" => "zh",
            "З" => "z",            "И" => "i",
            "Й" => "y",            "К" => "k",
            "Л" => "l",            "М" => "m",
            "Н" => "n",            "О" => "o",
            "П" => "p",            "Р" => "r",
            "С" => "s",            "Т" => "t",
            "У" => "u",            "Ф" => "f",
            "Х" => "x",            "Ц" => "ts",
            "Ч" => "ch",           "Ш" => "sh",
            "Щ" => "sh",           "Ь" => "'",
            "Ы" => "y",            "Ъ" => "'",
            "Э" => "e",            "Ю" => "yu",
            "Я" => "ya",           "а" => "a",
            "б" => "b",            "в" => "v",
            "г" => "g",            "д" => "d",
            "е" => "e",            "ё" => "e",
            "ж" => "zh",           "з" => "z",
            "и" => "i",            "й" => "y",
            "к" => "k",            "л" => "l",
            "м" => "m",            "н" => "n",
            "о" => "o",            "п" => "p",
            "р" => "r",            "с" => "s",
            "т" => "t",            "у" => "u",
            "ф" => "f",            "х" => "x",
            "ц" => "ts",           "ч" => "ch",
            "ш" => "sh",           "щ" => "sh",
            "ь" => "`",            "ы" => "y",
            "ъ" => "`",            "э" => "e",
            "ю" => "yu",           "я" => "ya",
            " " => "_",            "/" => "-",
            "\\" => "-");
  foreach ($a as $ru => $en) {
    $str = str_replace($ru, $en, $str);
  }
  return $str;
}
  

  function send_mail( $to, $subject, $message, $headers='' )
  {
    $message = str_replace( "\n", "<br>\n", $message );
    $subject = iconv( 'utf-8', 'koi8-r',$subject );
    $subject = $subject ? '=?koi8-r?B?'.base64_encode($subject).'?=' : '' ;
    $head  = "Content-type: text/html; charset=utf-8; \n";
    $head .= "From: ".from_email."\n";
    $head .= $headers;
    return mail( $to, $subject, $message, $head );
  }

function replace_once( $search, $replace, $subject ) {
  $st = strpos( $subject, $search );
  if ( $st !== false ) {
    $subject = substr( $subject, 0, $st ) . $replace . substr( $subject, $st+strlen($search) );
  }
  return $subject;
}


function mask( $str, $mask ) {
  if ( $str === $mask ) return true;
  $mi=0; $si=0; $ast=false; $mi2 = 0;
  while ( isset($str[$si]) &&
               ( isset($mask[$mi]) || $ast )
               ) {
    if ( isset($mask[$mi]) && $mask[$mi] == '*' ) {
      $ast = true;
      $mi2 = ++$mi;
      continue;
    }
    if ( isset($mask[$mi]) && ( $str[$si] === $mask[$mi] || $mask[$mi] == '?' ) ) {
      $mi++;
    } elseif ( $ast ) {
      $mi = $mi2;
    } else {
      return false;
    }
    $si++;
  }
  return !isset($str[$si]) && !isset($mask[$mi]);
}



class system {
  /**
   * active user
   * @var User
   */
  public static $user;
  
  public static function require_rights( $v ) {
    if ( self::$user->rights() >= $v ) {
      return true;
    }
    if ( self::$user->rights() == 0 ) {
      page::redirect( '/panel/login/?forbidden&redirect='.urlencode($_SERVER['REQUEST_URI']) );
    } else {
      $tmp = new Template( 'error_forbidden' );
      $tmp->flush();
    }
    die();
  }
  
  
}

class page {
  public static $URL;
  public static $page_id;
  public static $domain;
  public static $method;
  /**
   * html code template of processed page
   * @var Template
   */
  public static $html;
  public static $ajax = false;
  public static $title = '';
  public static $panel = false;


  /**
   * Get request url piece
   * @static
   * @param  $n int
   * @return string
   */
  public static function url( $n=null ) {
    if ( $n===null ) {
      $n = count(self::$URL)-1;
    }
    if ( $n===false ) {
      return implode( '/', self::$URL );
    }
    if ( array_key_exists( $n, self::$URL ) ) {
      return self::$URL[$n];
    }
    return null;
  }
  
  
  /**
   * Initiates page processing
   * @return void
   */
  public static function init() {
    self::$URL = explode('/', $_SERVER['REQUEST_URI']);
    array_shift(self::$URL);
    array_pop(self::$URL);
    array_walk( self::$URL, create_function('&$v','$v=urldecode($v);') );
    if ( empty(self::$URL[0]) ) {
      self::$page_id = 'home';
      self::$URL[0] = 'home';
    } else {
      self::$page_id = self::url(false);
    }
    self::$domain = $_SERVER['SERVER_NAME'];
    self::$method = $_SERVER['REQUEST_METHOD'];
    self::$ajax = is($_SERVER["HTTP_X_REQUESTED_WITH"])=='XMLHttpRequest'  || isset($_GET['ajax']);
  }
  
  
  
  public static function redirect( $url, $delay=0 ) {
    header( 'Refresh: '.$delay.'; URL='.$url );
  }
  
  public static function relocate( $url ) {
    header( 'Location: '.$url );
  }
  
  public static function not_found( ) {
    $tmp = new Template( 'error_not_found' );
    $tmp->flush();
    die();
  }
  
}

page::init();
?>